package org.ws.task.example.mq;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.ws.task.TaskMainBootstrap;
import org.ws.task.item.ExecuteContext;
import org.ws.task.item.PushTask;
import org.ws.task.model.NodeMetadata;
import org.ws.task.model.TaskItem;
import org.ws.task.repository.WorkerContextRepository;
import org.ws.task.zookeeper.ZkDataManager;

import javax.annotation.PostConstruct;
import java.io.FileNotFoundException;
import java.util.Collection;
import java.util.Map;

@Slf4j
@RestController
public class ExampleMqController {

    private FileLineItemProvider fileLineItemProvider;

    @Autowired
    private PushTask<String> uuidPushTask;

    @Autowired
    private PushTaskConfig.UuidItemProcessor uuidItemProcessor;

    @Value("${uuid-file-path}")
    private String uuidFilePath;

    @Autowired
    private TaskMainBootstrap taskMainBootstrap;

    @PostConstruct
    public void init() throws FileNotFoundException {
        fileLineItemProvider = new FileLineItemProvider(uuidFilePath);
    }


    @GetMapping("/run")
    public void run(){
        Collection<TaskItem<String>> items = fileLineItemProvider.getItems();
        while (CollectionUtils.isNotEmpty(items)){
            uuidPushTask.pushSync(items,3_000);
            items = fileLineItemProvider.getItems();
        }
        ExecuteContext context = WorkerContextRepository.getInstance().getContext("uuidPullTask");
        log.info("worker:");
        context.printSize();
        log.info("process count:{}",uuidItemProcessor.getCount());
    }

    @GetMapping("/test")
    public void test()throws Exception{
        ZkDataManager zkDataManager = taskMainBootstrap.getZkDataManager();
        String namespace = zkDataManager.getNamespace();
        log.info("namespace:{}",namespace);
        NodeMetadata leaderDataNode = zkDataManager.getLeaderDataNode();
        log.info("leaderDataNode:{}", JSON.toJSONString(leaderDataNode));
        Collection<Map<String, Object>> leaderNodes = zkDataManager.getLeaderNodes();
        log.info("leaderNodes:{}", JSON.toJSONString(leaderNodes));
        Collection<NodeMetadata> workerNodes = zkDataManager.getWorkerNodes();
        log.info("workerNodes:{}", JSON.toJSONString(workerNodes));
    }

}
